# coding:utf-8
# from django.shortcuts import render
from django.http import HttpResponse, HttpResponseNotAllowed
from WebHook.base_model import WeChat
from WeChat.models import AlarmRecord, EmployeeAndServiceInfo
from WebHook import settings
import json
import re
import time
import datetime
import logging

logger = logging.getLogger('django')

# Create your views here.


def msg_serialize(scope, name, ruleName, alarmMessage, alarmTime, url):
    msg = """
>
>范围：%s
>应用：<font color=\"warning\">%s</font>
>规则：%s
>信息：%s
>时间：%s
>地址: [%s](%s)
""" % (scope, name, ruleName, alarmMessage, alarmTime, url, url)
    return msg


def sls_serialize(
        trigger,
        namespace,
        container_name,
        pod_name,
        firetime,
        content):
    msg = """
>
>关键字：<font color=\"warning\">%s</font>
>命名空间：%s
>容器：%s
>Pod：%s
>时间：%s
>内容：%s

""" % (trigger, namespace, container_name, pod_name, firetime, content)
    return msg


def gitlab_project_destroy_serialize(
        event_name,
        name,
        owner_name,
        created_at,
        updated_at):
    msg = """
### gitlab事件通知
>
>事件名称：<font color=\"warning\">%s</font>
>项目名称：%s
>所有者：%s
>创建时间：%s
>更新时间：%s

""" % (event_name, name, owner_name, created_at, updated_at)
    return msg


def gitlab_group_destroy_serialize(
        event_name,
        name,
        created_at,
        updated_at):
    msg = """
### gitlab事件通知
>
>事件名称：<font color=\"warning\">%s</font>
>组名称：%s
>创建时间：%s
>更新时间：%s
""" % (event_name, name, created_at, updated_at)
    return msg


def gitlab_user_serialize(
        event_name,
        name,
        username,
        email,
        created_at,
        updated_at):
    msg = """
### gitlab事件通知
>
>事件名称：<font color=\"warning\">%s</font>
>用户名称：%s
>账号：%s
>邮箱：%s
>创建时间：%s
>更新时间：%s
""" % (event_name, name, username, email, created_at, updated_at)
    return msg


def SecondTimeTransfer(TimeBefore):
    """时间转换（格式精确到秒）

    :param TimeBefore:
    :return:
    """
    format_time = time.strptime(TimeBefore, "%Y-%m-%d %H:%M:%S")
    y, m, d, H, M, S = format_time[0:6]
    TimeEnd = datetime.datetime(y, m, d, H, M, S) + datetime.timedelta(hours=8)
    TimeEnd = TimeEnd.strftime("%Y-%m-%d %H:%M:%S")
    return TimeEnd


def get_tosuer(service_name):
    touser_list = []
    queryset = EmployeeAndServiceInfo.objects.filter(
        service_name=service_name).all()
    for item in queryset:
        touser_list.append(item.emp_id)
    touser = '|'.join(touser_list)
    return touser


def skywalking(request):
    """skywalking告警发送企业微信

    :param request:
    :return:
    """
    if request.method == 'POST':
        postBody = json.loads(request.body)
        print("postBody： %s" % postBody, flush=True)
        for item in postBody:
            scope = item['scope']
            name = item['name']
            ruleName = item['ruleName']
            alarmMessage = item['alarmMessage']
            startTime = item['startTime']
            print(startTime)
            print(type(startTime))
            # time_local = time.localtime(float(startTime / 1000 + 28800))
            time_local = time.localtime(startTime / 1000)
            alarmTime = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
            # 获取告警的小时信息
            matchObj = re.search(
                r'(.*) (.*?):(.*?):(.*?)',
                alarmTime,
                re.M | re.I)
            alarmHour = matchObj.group(2)
            print(alarmTime)
            # 判断告警时间，夜间入库
            if int(alarmHour) >= int(
                    settings.skywalking_night_start_time) or int(alarmHour) <= int(
                    settings.skywalking_night_end_time):
                created = AlarmRecord.objects.create(
                    scope=scope,
                    service_name=name,
                    rule_name=ruleName,
                    alarm_message=alarmMessage,
                    alarm_time=alarmTime,
                    business=settings.skywalking_business)
                logger.info("%s add to webhook" % created)
                continue
            # 工作时间，正常发送告警
            HINT_ORG = '### SkyWalking告警'
            msg = msg_serialize(
                scope,
                name,
                ruleName,
                alarmMessage,
                alarmTime,
                settings.skywalking_url)
            HINT_ORG += msg
            # 告警范围为"SERVICE_INSTANCE"，获取该实例所属服务名称
            instance_flag = 'false'
            last_name = ''
            if scope == "SERVICE_INSTANCE":
                instance_flag = "true"
                matchObj = re.search(
                    r'(.*)-pid(.*)',
                    name,
                    re.M | re.I)
                name = matchObj.group(1)
                last_name = matchObj.group(2)
            print(name)
            # 获取服务对应的开发人员企业微信id
            touser = get_tosuer(service_name=name)
            touser = "%s|%s" % (touser, settings.skywalking_touser)
            print(touser)
            W = WeChat(
                totag=settings.skywalking_totag,
                touser=touser,
                agentid=settings.skywalking_agentid)
            # 告警发送
            res = W.send_markdown(content=HINT_ORG)
            # 告警入库
            if instance_flag == 'true':
                name = "%s-pid%s" % (name, last_name)
            created = AlarmRecord.objects.create(
                scope=scope,
                service_name=name,
                rule_name=ruleName,
                alarm_message=alarmMessage,
                alarm_time=alarmTime,
                business=settings.skywalking_business)
            logger.info("%s add to webhook" % created)
            logger.info('{"status": 200, "info": "success"}')
        return HttpResponse('{"status": 200, "info": "success"}')
    else:
        logger.warning('{"status": 405, "info": "调用方法不被允许"}')
        return HttpResponse('{"status": 405, "info": "调用方法不对"}')


def sls_notify(request):
    """日志告警通知发送企业微信

    :param request:
    :return:
    """

    if request.method == "POST":
        # 获取POST请求体里的数据
        logger.info("body: %s" % request.body)
        # postBody = json.loads(request.body)
        postBody = request.body.decode(
            'utf-8').replace(': ', ':').replace('\n', '')
        logger.info("decode body: %s" % postBody)
        fireresult = re.search(
            '{(.*)\"trigger\":(.*),(.*)\"firetime\":(.*),(.*)\"rawcondition\":(.*),(.*)\"touser\":(.*),(.*)\"totag\":(.*),(.*)\"agentid\":(.*),(.*)\"fireresult\":(.*)}',
            postBody,
            re.S
        )

        trigger = eval(fireresult.group(2))
        firetime = eval(fireresult.group(4))
        rawcondition = eval(fireresult.group(6))
        touser = eval(fireresult.group(8))
        totag = eval(fireresult.group(10))
        agentid = eval(fireresult.group(12))
        result = fireresult.group(14).replace('\n', '')

        content = re.search(
            '{(.*)\"_container_name_\":(.*),(.*)\"_image_name_\"(.*)\"_namespace_\":(.*),(.*)\"_pod_name_\":(.*),(.*)\"_pod_uid_\"(.*)\"content\":(.*)}',
            result,
            re.S
        )

        container_name = eval(content.group(2))
        namespace = eval(content.group(5))
        pod_name = eval(content.group(7))
        content = eval(content.group(10))

        logger.info("trigger: %s" % trigger)
        logger.info("firetime: %s" % firetime)
        logger.info("namespace: %s" % namespace)
        logger.info("container_name: %s" % container_name)
        logger.info("pod_name: %s" % pod_name)
        logger.info("rawcondition: %s" % rawcondition)
        logger.info("content: %s" % content)
        logger.info("touser: %s" % touser)
        logger.info("totag: %s" % totag)
        logger.info("agentid: %s" % agentid)

        W = WeChat(totag=totag, touser=touser, agentid=agentid)
        context = sls_serialize(
            trigger,
            namespace,
            container_name,
            pod_name,
            firetime,
            content)
        res = W.send_markdown(content=context)
        logger.info("return: %s" % res)
        logger.info('{"status": 200, "info": "success"}')
        return HttpResponse('{"status": 200, "info": "success"}')
    else:
        logger.warning('{"status": 405, "info": "调用方法不被允许"}')
        return HttpResponseNotAllowed(['POST'])


def kafka_eagle(request):
    """kafka-eagle告警发送企业微信

    :param request:
    :return:
    """
    if request.method == "POST":
        try:
            postBody = json.loads(request.body)
            content = postBody['markdown']['content']
            logging.info("postBody: %s" % postBody)
            W = WeChat(
                totag=settings.kafka_eagle_totag,
                touser=settings.kafka_eagle_touser,
                agentid=settings.kafka_eagle_agentid)
            res = W.send_markdown(content=content)
            return HttpResponse(json.dumps(res))
        except Exception as e:
            print(e)
            return HttpResponse('{"status": 500, "info": "调用接口，出现异常"}')

    else:
        logger.warning('{"status": 405, "info": "调用方法不被允许"}')
        return HttpResponseNotAllowed(['POST'])


def gitlab(request):
    """接收gitlab触发的事件，发送企业微信

    :param request:
    :return:
    """

    if request.method == "POST":
        try:
            postBody = json.loads(request.body)
            logger.info(type(postBody))
            logger.info(postBody)
            msg = ""
            if "event_name" in postBody.keys():
                if postBody['event_name'] == "project_destroy":
                    # created_at = SecondTimeTransfer(postBody['created_at'].replace('T', ' ').replace('Z', ''))
                    # updated_at = SecondTimeTransfer(postBody['updated_at'].replace('T', ' ').replace('Z', ''))
                    msg = gitlab_project_destroy_serialize(
                        postBody['event_name'],
                        postBody['name'],
                        postBody['owner_name'],
                        postBody['created_at'],
                        postBody['updated_at'])
                elif postBody['event_name'] == "group_destroy":
                    # created_at = SecondTimeTransfer(postBody['created_at'].replace('T', ' ').replace('Z', ''))
                    # updated_at = SecondTimeTransfer(postBody['updated_at'].replace('T', ' ').replace('Z', ''))
                    msg = gitlab_group_destroy_serialize(
                        postBody['event_name'],
                        postBody['name'],
                        postBody['created_at'],
                        postBody['updated_at'])
                elif postBody['event_name'] in ['user_create', 'user_destroy', 'user_failed_login']:
                    # created_at = SecondTimeTransfer(postBody['created_at'].replace('T', ' ').replace('Z', ''))
                    # updated_at = SecondTimeTransfer(postBody['updated_at'].replace('T', ' ').replace('Z', ''))
                    msg = gitlab_user_serialize(postBody['event_name'],
                                                postBody['name'],
                                                postBody['username'],
                                                postBody['email'],
                                                postBody['created_at'],
                                                postBody['updated_at'])
                else:
                    pass
            elif "object_kind" in postBody.keys():
                pass
            else:
                pass
            if msg:
                # 发送到企业微信
                W = WeChat(
                    totag=settings.gitlab_totag,
                    toparty=settings.gitlab_toparty,
                    touser=settings.gitlab_touser,
                    agentid=settings.gitlab_agentid)
                res = W.send_markdown(content=msg)
                return HttpResponse('{"status": 200, "info": %s}' % res)
            else:
                return HttpResponse('{"status": 200, "info": 该事件不处理}')
        except Exception as e:
            print(e)
            return HttpResponse('{"status": 500, "info": "调用接口，出现异常"}')
    else:
        logger.warning('{"status": 405, "info": "调用方法不被允许"}')
        return HttpResponseNotAllowed(['POST'])
